from django.db import models


def get_namespace(flag = False):
    try:
        namespace_data = Namespace.objects.filter(enabled=True, deleted=False)
        choices = [(item.namespace, item.label) for item in namespace_data]
        return choices
    except:
        return []


class BasicModel(models.Model):
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    enabled = models.BooleanField(default=True)
    deleted = models.BooleanField(default=False)

    class Meta:
        abstract = True

    
    def delete(self):
        self.deleted = True
        self.save()


class Namespace(BasicModel):
    namespace = models.CharField(max_length=64, verbose_name='命名空间', help_text='若生成文件时, 此字段会成为文件名', unique=True)
    label = models.CharField(max_length=256, verbose_name='命名空间中文名称', help_text='可读性较强的名称', unique=True)
    description = models.TextField(verbose_name='描述信息', help_text='命名空间的的描述信息', blank=True, null=True)

    class Meta:
        db_table = 'namespace'
        verbose_name = "命名空间"
        verbose_name_plural = "命名空间"

    def __str__(self):
        return f'{self.label} ({self.namespace})'
    


class Transition(BasicModel):
    CODE_CHOICES = (
        ('en-US', '美式英语'),
        ('zh-CN', '简体中文'),
        ('zh-TW', '繁体中文, 台湾'),
        ('zh-HK', '繁体中文, 香港'),
    )
    namespace = models.CharField(max_length=64, verbose_name='命名空间', help_text='数据所在的命名空间', choices=get_namespace())
    path = models.CharField(max_length=256, verbose_name='路径', help_text='根据命名空间寻求值的路径')
    code = models.CharField(max_length=32, verbose_name='语言代码', help_text='数据对应语言代码', choices=CODE_CHOICES)
    language = models.TextField(verbose_name='语言数据', blank=True, null=True)

    def __init__(self, *args, **kargs):
        super(Transition, self).__init__(*args, **kargs)
        self._meta.get_field('namespace').choices = get_namespace(True)

    class Meta:
        db_table = 'transition'
        unique_together = ('namespace', 'path', 'code')
        verbose_name = "语言数据"
        verbose_name_plural = "语言数据"

    def __str__(self):
        return self.code + ' ' + ((self.language[13]+'...') if len(self.language) > 12 else self.language)
